import { useNavigate } from 'react-router-dom';
import { Image} from '@douyinfe/semi-ui';
import { useSelector } from 'react-redux';
import Cookies from 'js-cookie';
import logo from '@/assets/images/logo.svg';
import retreat from '@/assets/images/retreat.svg';
import styles from './index.module.scss';
import auth from '@/api/auth';
import { Dropdown, Menu } from '@arco-design/web-react';

export default function Header({ 
  showLogo = true,
  cursor=true, 
  title = '',
  backHome=false
}) {
  const navigate = useNavigate();
  const isLoggedIn = useSelector(state => state.auth.token);
  const user = useSelector(state => state.auth.user);

  const handleBack = () => {
    const canGoBack = window.history.state && window.history.state.idx > 0;
    canGoBack ? navigate(-1) : navigate('/');
  };
  const handleIndex = () => {
    navigate("/");
  };

  const handleLogout = () => {
    auth.logout().then(()=>{
      Cookies.remove('token');
      Cookies.remove('user');
      setTimeout(() => {
          window.location.href = '/login';
      }, 100);
    })
  };
  return (
    <div className={showLogo?styles.headerSection:styles.headerSectionEdit}>
      <div className={showLogo?styles.header:styles.headerEdit}>
        <div className={styles.headerLeft}>
          {showLogo ? (
            <div className={styles.logoContainer}>
              <Image src={logo} preview={false} className={`${styles.logoImage}  ${cursor&&styles.cursor}`} draggable={false} onClick={cursor?handleIndex:undefined} />
            </div>
          ) : (
            <div className={`${styles.backContainer} ${cursor&&styles.cursor}`} onClick={ backHome ? handleIndex : cursor&&handleBack}>
              <Image
                src={retreat}
                preview={false}
                className={styles.backIcon}
                draggable={false}
              />
              <div>返回</div>
            </div>
          )}
        </div>
        <div className={styles.headerTitle}>
          <div className={styles.headerTitleText}>{title}</div>
        </div>
        <div className={styles.headerRight}>
          {isLoggedIn && (
            <Dropdown
              position='bl'
              trigger='click'
              droplist={
                <Menu style={{ padding: "0",maxHeight:'unset' }}>
                  <Menu.Item onClick={handleLogout}>退出登录</Menu.Item>
                </Menu>
              }
            >
              <div className={styles.dropdownContainer}>
                <div className={styles.rightContent}>
                  <div>{user?.username||'默认用户'}</div>
                </div>
              </div>
            </Dropdown>
          )}
        </div>
      </div>
    </div>
  );
}